package com.android.nearshop.app;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Process;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;

import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.business.model.Addr;
import com.android.nearshop.business.update.UpdateManager;
import com.android.nearshop.io.database.DB;
import com.android.nearshop.io.database.SearKeyDB;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.ImageLoader;
import com.android.nearshop.util.Util;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-6
 * @see : 应用上下文
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class MyApplication extends Application 
{
    private static MyApplication instance;
    public Handler mHandler;
    public SharedPreferences mPreference;
    public boolean isFirst = true;
    public boolean isGpsTip = false;
    public boolean isShortCutTip = false;
    public boolean isLastVer = false;
    
    @Override
    public void onCreate()
    {
        super.onCreate();
        instance = this;
        mHandler = new Handler();
        mPreference = PreferenceManager.getDefaultSharedPreferences(this);
        MyBMapManager.getInstace(this);
        DB.initDB(this);
        ImageLoader.init(this, 0, Util.getExternDir("/nearshop/img/"));
        restore();
    }
    
    @Override
    public void onTerminate()
    {
        MyBMapManager.getInstace(this).destory();
        DB.closeDB();
        super.onTerminate();
    }
    
    public void exit()
    {
        MyBMapManager.getInstace(this).destory();
        UpdateManager.getInstacnce(this).destory();
        Process.killProcess(Process.myPid());
    }
    
    public static MyApplication getContext()
    {
        return instance;
    }

    public boolean isNetWorkAvailable()
    {
        ConnectivityManager connectMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectMgr.getActiveNetworkInfo() != null)
        {
            return connectMgr.getActiveNetworkInfo().isAvailable();
        }else
        {
            return false;
        }
    }
    
    // 判断是否是 3G 或者 wifi 网络
    public boolean isWifi3GNetwork()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        TelephonyManager tele = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        if (activeNetInfo != null)
        { 
            if(activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) 
            {  
                return true;  
            }else
            if(activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            {
                return Util.isConnectionFast(activeNetInfo.getType(), tele.getNetworkType());
            }else 
            {
                return false;
            }
        }else
        {
            return false;
        }
    }
    
    // 是否需要引导页
    public boolean isNeedGuide()
    {
        boolean r = mPreference.getBoolean(Constant.KEY_NEED_GUIDE, true);
        if(r)
        {
            mPreference.edit().putBoolean(Constant.KEY_NEED_GUIDE, false).commit();
        }
        // 暂时无需引导视图
        return (r && false);
    }
    // 是否打开广告
    public boolean isAdvOn()
    {
        return mPreference.getBoolean(Constant.KEY_ADV_ON, true);       
    }
    // 设置广告开关
    public void setAdvOn(boolean on)
    {
        mPreference.edit().putBoolean(Constant.KEY_ADV_ON, on).commit();
    }
    
    public String getStartImg()
    {
        return mPreference.getString(Constant.KEY_START_IMG, null);
    }
    
    public void setStartImg(String imgPath)
    {
        mPreference.edit().putString(Constant.KEY_START_IMG, imgPath).commit();
    }
    // 是否音效开关
    public boolean isSoundOn()
    {
        return mPreference.getBoolean(Constant.KEY_SOUND_ON, true);
    }    
    // 设置音效开关
    public void setSoundOn(boolean on)
    {
        mPreference.edit().putBoolean(Constant.KEY_SOUND_ON, on).commit();
    }
    // 设置关键字保存天数
    public void setKeywordSaveDays(int days)
    {
        mPreference.edit().putInt(Constant.KEY_KEYWORD_SAVA_DAYS, days).commit();
    }
 // 获得关键字保存天数
    public int getKeywordSaveDays()
    {
    	return mPreference.getInt(Constant.KEY_KEYWORD_SAVA_DAYS, 30);
    }
    
    // 是否快捷开关
    public boolean isShortCut()
    {
        return mPreference.getBoolean(Constant.SHORTCUT_MARK_NAME, false);
    }    
    // 设置快捷开关
    public void setShortCut(boolean have)
    {
        mPreference.edit().putBoolean(Constant.SHORTCUT_MARK_NAME, have).commit();
    }
    //////////////////////////////////////////////////////////////////////////////////////
    private int mCurLocMode = Constant.LOC_CUR;
    private Addr mSpecAddr;
    private int mSpecCityId;
       
    // 恢复配置值
    private void restore()
    {
        mCurLocMode = mPreference.getInt(Constant.KEY_LOC_MODE, Constant.LOC_CUR);
        
        mSpecAddr = new Addr();
        mSpecAddr.longitude  = mPreference.getFloat(Constant.KEY_LON, 0.0f);
        mSpecAddr.latitude  = mPreference.getFloat(Constant.KEY_LAT, 0.0f);
        mSpecAddr.district = mPreference.getString(Constant.KEY_DISTRICT, "区域");
        
        mSpecCityId = mPreference.getInt(Constant.KEY_SPEC_CITYID, 0);
        //清除过期关键字
        SearKeyDB.clearPreNDay(getKeywordSaveDays());
        //打开广告
        setAdvOn(true);
    }
    
    /**
     * 设置为 地图选取模式
     */
    public void setLocMapMode(Addr addr)
    {
        mCurLocMode = Constant.LOC_MAP;
        mSpecAddr  = addr;
        
        mPreference.edit().putInt(Constant.KEY_LOC_MODE, Constant.LOC_MAP).commit();
        mPreference.edit().putFloat(Constant.KEY_LON, (float)addr.longitude).commit();
        mPreference.edit().putFloat(Constant.KEY_LAT, (float)addr.latitude).commit();
        if(addr.district!=null)
        {
            mPreference.edit().putString(Constant.KEY_DISTRICT, addr.district).commit();
        }
        // 获取地址
        MyBMapManager.getInstace(this).startAddr(MyBMapManager.getInstace(this).getMyLoation());
    }

    /**
     * 设置为 城镇选取模式
     */
    public void setLocCityMode(int cityId)
    {
        mCurLocMode = Constant.LOC_CITY;
        mSpecCityId = cityId;
        
        mPreference.edit().putInt(Constant.KEY_LOC_MODE, Constant.LOC_CITY).commit();
        mPreference.edit().putInt(Constant.KEY_SPEC_CITYID, cityId).commit();
        // 防止载入时，镇区延后载入找不到位置的情况
        Location loc = DataCacheManager.getInstance().getLocationByAId(cityId);
        if(loc != null)
        {
            mPreference.edit().putFloat(Constant.KEY_LON, (float)loc.getLongitude()).commit();
            mPreference.edit().putFloat(Constant.KEY_LAT, (float)loc.getLatitude()).commit();
            // 获取地址
            MyBMapManager.getInstace(this).startAddr(loc);
        }       
    }
    
    /**
     * 设置为 当前位置选取模式
     */
    public void setLocCurMode()
    {
        mCurLocMode = Constant.LOC_CUR;
        mPreference.edit().putInt(Constant.KEY_LOC_MODE, Constant.LOC_CUR).commit();
    }    
    //////////////////////////////////////////////////////////////////////////////////////
    /**
     * 获取地图选择的地址对象
     * @return
     */
    public Addr getLocMapValue()
    {      
        return mSpecAddr;
    }
    
    /**
     * 获取地图选择的镇区名称
     * @return
     */
    public String getLocMapDistrict()
    {   
        return mSpecAddr.district;
    }
    
    /**
     * 获取城镇选择的城市id
     * @return
     */
    public int getLocCityValue()
    {
        return mCurLocMode == Constant.LOC_CITY ? mSpecCityId : 0;
    }
        
    /**
     * 获取当前位置选择模式
     * @return
     */
    public int getLocMode()
    {
        return mCurLocMode;
    }

    // 获取最后保存的坐标，当无法获取坐标时
    public Location getLastLocation()
    {
        Location loc = new Location("last");
        loc.setLongitude(mPreference.getFloat(Constant.KEY_LON, 0.0f));
        loc.setLatitude(mPreference.getFloat(Constant.KEY_LAT, 0.0f));
        return loc.getLongitude() > 1.0f ? loc : null;
    }
}
